package com.csw.shuanfa.utils;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;

/**
 * @author 1
 */
public class ImageChangeUtil {

    public static void main(String[] args) throws Exception {
        String inputFilePath = "C:\\Users\\1\\Desktop\\音频测试\\弹窗\\插图.webp";
        String outputFilePath = "C:\\Users\\1\\Desktop\\音频测试\\弹窗\\捕获.jpg";
        File input = new File(inputFilePath);
        BufferedImage image = ImageIO.read(input);
        BufferedImage resized = resize(image, 1655, 2340);
        File output = new File(outputFilePath);
        /*可以调整为转换成任何格式,经测试jpeg和png可以，HEIC,tiff,webp不行*/
        ImageIO.write(resized, "jpg", output);
    }

    /**
     * 不按比例缩放
     */
    private static BufferedImage resize(BufferedImage img, int height, int width) {
        Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resized.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return resized;
    }

    /**
     * 按比例缩放
     */
    private static BufferedImage resizebyaspect(BufferedImage img, int height, int width) {
        int oriWidth = img.getWidth();
        int oriHeight = img.getHeight();
        BigDecimal ccc = BigDecimal.valueOf(width).divide(BigDecimal.valueOf(oriWidth));
        float ratioW = ccc.floatValue();
        BigDecimal ddd = BigDecimal.valueOf(height).divide(BigDecimal.valueOf(oriHeight));
        float ratioH = ddd.floatValue();
        BigDecimal eee = BigDecimal.valueOf(ratioH).divide(BigDecimal.valueOf(oriWidth));
        int newWidth = (ratioW < ratioH) ? width : eee.intValue();
        BigDecimal fff = BigDecimal.valueOf(ratioW).divide(BigDecimal.valueOf(oriHeight));
        int newHeight = (ratioH < ratioW) ? height : fff.intValue();
        Image tmp = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
        BufferedImage resized = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resized.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return resized;
    }
}
